import { Typography } from 'antd';
import React, { ReactNode } from 'react';

interface ItemProps<T> {
  title: ReactNode;
  key: string;
  children?: T[];
}

interface GroupTileProps<T> {
  items?: ItemProps<T>[];
  onClick?(e: React.MouseEvent<HTMLHeadElement>, item: ItemProps<T>): void;
  onChildClick?(e: React.MouseEvent<HTMLLIElement>, item: ItemProps<T>, child: T): void;
  render(value: T): ReactNode;
}
export function GroupTile<T extends { key: string }>({ items, onClick, render, onChildClick }: GroupTileProps<T>) {
  return (
    <ul style={{ display: 'flex', flexDirection: 'column', rowGap: 16 }}>
      {items
        ?.filter((v): v is Required<ItemProps<T>> => Boolean(v.children?.length))
        .map((item) => {
          const { title, key, children } = item;
          return (
            <li key={key}>
              <Typography.Title
                level={4}
                onClick={(e) => {
                  onClick?.(e, item);
                }}
              >
                {title}
              </Typography.Title>
              <ul style={{ display: 'flex', columnGap: 16 }}>
                {children.map((child) => {
                  return (
                    <li
                      key={child.key}
                      onClick={(e) => {
                        onChildClick?.(e, item, child);
                      }}
                    >
                      {render(child)}
                    </li>
                  );
                })}
              </ul>
            </li>
          );
        })}
    </ul>
  );
}
